import IconFontCN from '@/components/IconFontCN';
import { OrderStatus } from '@/constants/commonConst';
import {
  getTakeAwayUserOrderById,
  getTakeAwayUserOrderAll,
  getTakeAwayUserOrderPageList,
  commonUpdate,
  updateTakeAwayUserOrder,
  addTakeAwayUserOrder,
  deleteTakeAwayUserOrder
} from '@/services/takeAwayUserOrderService';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, message, Popconfirm, Select, Space, Switch, Typography } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import DetailPage from './detail';
import BackColor from 'wangeditor/dist/menus/back-color';
import BackOrderPage from './backOrder';
import { getCookie } from '@/utils/cookieUtils';
import { dateFormat } from '@/utils/common';

/**
 *
 * @constructor
 */
const TakeAwayUserOrderPage: React.FC<unknown> = () => {
  const shopId = parseInt(getCookie("shopId") ?? "0");
  const [updateData, setUpdateData] = useState<TakeAwayUserOrderType.TakeAwayUserOrder>();
  const [backOrder, setBackOrder] = useState<TakeAwayUserOrderType.TakeAwayUserOrder>();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [backOrderVisible, setBackOrderVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  /**
   *
   * @param
   */
  const doDelete = async (model: TakeAwayUserOrderType.TakeAwayUserOrder) => {
    const hide = message.loading('正在删除');
    if (!model?.Id) {
      return;
    }
    try {
      await deleteTakeAwayUserOrder({
        id: model.Id,
      });
      message.success('操作成功');
      actionRef.current?.reload();
    } catch (e: any) {
      message.error('操作失败，' + e.message);
    } finally {
      hide();
    }
  };

  const updateOrder = async (record: TakeAwayUserOrderType.TakeAwayUserOrder, status: string) => {
    const { StatusCode } = await commonUpdate(record.Id, "Status", status);
    if (StatusCode === 0) {
      message.success("操作成功！")
    } else {
      message.error("操作失败！")
    }
    actionRef.current?.reload();
  }

  useEffect(() => {
    actionRef.current?.reload();
  }, [shopId])

  /**
   *
   */
  const columns: ProColumns<TakeAwayUserOrderType.TakeAwayUserOrder>[] = [
    {
      title: '下单人',
      dataIndex: 'OrderUserName'
    },
    {
      title: '订单号',
      dataIndex: 'OrderNumber'
    },
    {
      title: '下单时间',
      dataIndex: 'AddTime',
      hideInSearch: true,
      renderText(text, record) {
        return dateFormat(record.AddTime, 'yyyy-mdd-dd hh:mm:ss')
      },
    },
    {
      title: '堂食',
      dataIndex: 'IsTakeAway',
      hideInSearch: true,
      render(dom, entity) {
        return <Switch checked={entity.IsTakeAway === 1} />;
      },
    },
    {
      title: '取单号',
      dataIndex: 'TakeAwayNumber'
    },
    {
      title: '支付方式',
      dataIndex: 'PayType',
      hideInSearch: true,
      renderText(text, record) {
        return record.PayType == 1 ? "余额支付" : "微信支付";
      },
    },
    {
      title: '电话',
      dataIndex: 'UserPhone',
      hideInSearch: true,
    },
    {
      title: '价格',
      dataIndex: 'Price',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'Status',
      renderText(text, record) {
        if (record.IsTakeAway === 1) {
          if (record.Status === 1)
            return "待制作";
          else if (record.Status === 2) {
            return "制作完成，待取餐";
          }
        }

        return OrderStatus.find(r => r.value === record.Status)?.label;
      },
      renderFormItem: () => {
        const list = OrderStatus;
        const options = list.map(item => <option key={item.value}>{item.label}</option>);
        return (
          <Select
            key="Status"
            showSearch
            placeholder="请输入关键字搜索"
            filterOption={false}
          >   {
              <>
                <option key="" value="">全部</option>
              </>
            }
            {options}
          </Select>
        )
      }
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_: any, record: any) => (
        <Space split={<Divider type="vertical" />}>

          <IconFontCN title='详情' onClick={() => { setModalVisible(true); setUpdateData(record); }} typeString='icon-a-xiangqingpicixiangqingpandianxiangqing' />
          {
            record.Status === 0 ?
              <Popconfirm
                title="确定接单吗？"
                onConfirm={() => updateOrder(record, "1")}
                okText="确认"
                cancelText="取消"
              >
                <IconFontCN title='接单' onClick={() => { }} typeString='icon-daijiedan' />
              </Popconfirm>
              : null
          }
          {
            record.Status === 1 ? <Popconfirm
              title={record.IsTakeAway === 1 ? "确定制作完成吗？" : "确定开始配送吗？"}
              onConfirm={() => updateOrder(record, "2")}
              okText="确认"
              cancelText="取消"
            >
              <IconFontCN title={record.IsTakeAway === 1 ? '制作完成' : '配送'} onClick={() => { }} typeString={record.IsTakeAway === 1 ? 'icon-shiwu-163-copy' : 'icon-waimai'} />
            </Popconfirm> : null
          }
          {
            record.Status === 2 ?
              <Popconfirm
                title={"确定完成订单吗？"}
                onConfirm={() => updateOrder(record, "3")}
                okText="确认"
                cancelText="取消"
              >
                <IconFontCN title='订单完成' onClick={() => { }} typeString='icon-a-wancheng1' />
              </Popconfirm>
              : null
          }
          <IconFontCN title='退款' onClick={() => { setBackOrder(record); setBackOrderVisible(true) }} typeString='icon-tianmao-jisutuikuan' />
          <Popconfirm
            title="您确定要删除么？"
            onConfirm={() => doDelete(record)}
            okText="确认"
            cancelText="取消"
          >
            <Typography.Link type="danger">删除</Typography.Link>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<TakeAwayUserOrderType.TakeAwayUserOrder>
        headerTitle="管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
          >
            新建
          </Button>,
        ]}
        request={async (params: any, sorter: any) => {
          const searchParams: PageInfo.PageRequest = {
            pageSize: params.pageSize,
            current: params.current
          };

          let sortQuery = "", filterQuery = `eq(ShopId,${shopId})&isnull(IsPredetermine)`;
          // eslint-disable-next-line guard-for-in
          for (const key in sorter) {
            sortQuery += `${key}|${sorter[key]}`;
          }

          if (sortQuery != "") {
            searchParams['@sort'] = sortQuery;
          }

          for (const key in params) {
            if (key !== "pageSize" && key !== "current") {
              if (params[key] != "") {
                if (key === "Status") {
                  filterQuery += `&eq(${key},${params[key]})&`;
                  params[key] = '';
                } else {
                  filterQuery += `&contains(${key},${params[key]})&`;
                  params[key] = '';
                }
              }
            }
          }

          if (filterQuery != "") {
            searchParams['@filter'] = filterQuery;
          }

          searchParams['@relationships'] = "UserInfo";
          const { Items, StatusCode } = await getTakeAwayUserOrderPageList(searchParams);
          return {
            data: Items[0]?.Records || [],
            success: StatusCode === 200,
            total: Items[0].Total,
          } as any;
        }}
        columns={columns}
      />
      {updateData ? <DetailPage id={updateData?.Id} onClose={() => setModalVisible(false)} modalVisible={modalVisible} /> : null}
      {backOrder ? <BackOrderPage id={backOrder?.Id} onClose={() => setBackOrderVisible(false)} modalVisible={backOrderVisible} /> : null}
    </PageContainer>
  );
};

export default TakeAwayUserOrderPage;
